package com.hujing;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 并发编程示例1
 * 使用多线程计算1-1000的和
 */
public class ConcurrentDemo1 {
    
    private static int count = 0;
    private static final ConcurrentHashMap<String, ReentrantLock> lockMap = new ConcurrentHashMap();
    private static final CountDownLatch latch = new CountDownLatch(10000);

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0;i<10000;i++){
            new Thread(()->add()).start();
        }
        // 主线程阻塞，直到减数器为0，即所有子线程执行完毕
        latch.await();
        System.out.println("count="+count);
    }
    
    public static void add(){
        ReentrantLock lock = lockMap.computeIfAbsent(ConcurrentDemo1.class.getName(), k -> new ReentrantLock());
        lock.lock();
        try{
            count++;
        }finally{
            lock.unlock();
            // 子线程执行完毕，计数器减1
            latch.countDown();
        }
    }
}
